import { stringify } from 'querystring';
import { history } from 'umi';
import {
  sMQcode,
  queryQcode,
  fakeAccountLogin,
  logout,
  quickLogin,
  quickLoginCall,
  quickToken,
} from '@/services/login';
import { setAuthority, delCookie, setCookie, getCookie } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { notification } from 'antd';
import Cookies from 'js-cookie';

const Model = {
  namespace: 'login',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);

      if (response.status === 200) {
        yield put({
          type: 'changeLoginStatus',
          payload: response.data,
        }); // Login successfully

        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        setCookie('tks', response.data.token);
        setCookie('loginId', response.data.loginId);
        clearInterval(payload.sMtid);
        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/welcome');
      } else {
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        }); // Login successfully
      }
    },
    *sMQcode({ payload, callback }, { call }) {
      let id = null;
      if (Cookies.get('loginId')) {
        id = Cookies.get('loginId');
      }
      const LoginId = { loginId: id };
      const param = { ...payload, ...LoginId };

      const response = yield call(sMQcode, param);
      if (response.status === 200) {
        if (callback && typeof callback === 'function') {
          callback(response); // 返回结果
        }
      } else {
        notification.error({
          message: response.msg,
        });
      }
    },
    *queryToken({ payload }, { call, put }) {
      const response = yield call(queryQcode, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response.data,
      }); // qcode Login successfully

      if (response.status === 200) {
        clearInterval(payload.sTid);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        setCookie('tks', response.data.token);
        setCookie('loginId', response.data.loginId);
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/welcome');
      }
    },
    // eslint-disable-next-line no-unused-vars
    *quickLogin({ payload, callback }, { call }) {
      let id = null;
      if (Cookies.get('loginId')) {
        id = Cookies.get('loginId');
      }
      const LoginId = { loginId: id };

      const response = yield call(quickLogin, LoginId);
      if (response.status === 200) {
        if (callback && typeof callback === 'function') {
          callback(response); // 返回结果
        }
      } else {
        notification.error({
          message: response.msg,
        });
      }
    },
    *quickLoginCallBack({ payload }, { call, put }) {
      const response = yield call(quickLoginCall, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response.data,
      }); // qcode Login successfully

      if (response.status === 200) {
        clearInterval(payload.sTid);
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        setCookie('tks', response.data.token);
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/welcome');
      }
    },
    *quickToken({ payload, callback }, { call, put }) {
      let id = null;
      if (Cookies.get('loginId')) {
        id = Cookies.get('loginId');
      }
      const formData = new FormData();
      formData.append('loginId', id);
      formData.append('username', payload.username);
      formData.append('dynamicToken', payload.dynamicToken);

      const response = yield call(quickToken, formData);
      yield put({
        type: 'changeLoginStatus',
        payload: response.data,
      }); // qcode Login successfully

      if (response.status === 200) {
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        setCookie('tks', response.data.token);
        setCookie('loginId', response.data.loginId);
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);

            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }

        history.replace(redirect || '/welcome');
      } else {
        if (callback && typeof callback === 'function') {
          callback(response); // 返回结果
        }
      }
    },
    *logout({ payload }, { call }) {
      // eslint-disable-next-line no-param-reassign
      payload = getCookie('tks');
      const response = yield call(logout, payload);
      if (response.status === 200) {
        const { redirect } = getPageQuery(); // Note: There may be security issues, please note

        if (window.location.pathname !== '/user/login' && !redirect) {
          history.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          });
        }
        // sessionStorage.removeItem("authority");
        delCookie('authority');
        delCookie('tks');
      } else {
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      console.log(payload);
      console.log(payload.currentAuthority);
      setAuthority(payload.currentAuthority);
      return { ...state, status: payload.status, type: payload.type };
    },
  },
};
export default Model;
